package cn.mooncode.basketballManage.controller;

import cn.mooncode.basketballManage.pojo.*;
import cn.mooncode.basketballManage.service.IRoleService;
import cn.mooncode.basketballManage.service.IUserRoleService;
import cn.mooncode.basketballManage.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @program: basketballManage
 * @description: 登录
 * @author: jinweizhi
 * @create: 2021-03-28 10:50
 **/

@Api(tags = "LoginController")
@RestController
public class LoginController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUserRoleService userRoleService;

    @ApiOperation(value = "登录返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody UserLoginParam userLoginParam, HttpServletRequest request) {
        return userService.login(userLoginParam.getUsername(), userLoginParam.getPassword(), request);
    }

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    @Transactional
    public RespBean register(@RequestBody User user) {
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        user.setIsenabled(true);
        if (userService.save(user)) {
            //        默认角色为角色表中第一条数据
            List<Role> list = roleService.list();
            Role role = list.get(0);
            UserRole userRole = new UserRole();
            userRole.setRid(role.getId());
            userRole.setUid(user.getId());
            userRoleService.save(userRole);
            return RespBean.success("注册成功！");
        }
        return RespBean.error("注册失败！");
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout() {
        return RespBean.success("退出成功！");
    }
}
